package cn.yunyichina.provider.base.service.impl;

import cn.yunyichina.provider.base.dao.*;
import cn.yunyichina.provider.base.entity.*;
import cn.yunyichina.provider.base.vo.*;
import cn.yunyichina.provider.framework.annotation.validate.ValidateException;
import cn.yunyichina.provider.framework.annotation.validate.Validator;
import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.framework.dubbo.service.BoneService;
import cn.yunyichina.provider.framework.dubbo.service.CacheService;
import cn.yunyichina.provider.framework.dubbo.service.HisifaceService;
import cn.yunyichina.provider.framework.dubbo.service.MessageService;
import cn.yunyichina.provider.iface.entity.PersonalUser;
import cn.yunyichina.provider.iface.entity.PersonalUserOpenid;
import cn.yunyichina.provider.iface.entity.base.Org;
import cn.yunyichina.provider.iface.entity.cache.SessionInfo;
import cn.yunyichina.provider.iface.entity.cache.SysUserOrg;
import cn.yunyichina.provider.iface.entity.common.ResCommon;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.common.ResponseObject;
import cn.yunyichina.provider.iface.entity.hisiface.base.PatientVo;
import cn.yunyichina.provider.iface.entity.hisiface.base.PatientVoResponse;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.commons.IDUtils;
import cn.yunyichina.utils.commons.IdCardUtils;
import cn.yunyichina.utils.commons.MobileUtil;
import cn.yunyichina.utils.convert.JsonUtils;
import cn.yunyichina.utils.security.MD5Util;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 *
 *
 * 项目名称：yyt-provider-base
 * 类名称：UserServiceImpl
 * 类描述：    涉及到用户类实现（医院用户登录）
 * 创建人：zhangkewen
 * 创建时间：2016年9月20日 下午5:13:58
 * 修改人：zhangkewen
 * 修改时间：2016年9月20日 下午5:13:58
 * 修改备注：
 * @version
 *
 */
@Service
public class UserServiceImpl {
    private static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    HospitalUserDao hospitalUserDao;

    @Autowired
    private OrgUserDao orgUserDao;

    @Autowired
    private PersonalUserDao personalUserDao;

    @Autowired
    PersonalUserFamilyDao personalUserFamilyDao;

    @Autowired
    private PersonalUserOpenidDao personalUserOpenidDao;

    @Autowired
    private DeptUserRelationDao deptUserRelationDao;

    @Autowired
    private OrgUserOpenidDao orgUserOpenidDao;

    @Autowired
    private OrgDao orgDao;


    public ResponseObject loginUserHospital(String data) {
        ResponseObject response = new ResponseObject();
        LoginUserVoRequest loginUserVo=JsonUtils.parseObject(data,LoginUserVoRequest.class);

        if(StringUtils.isBlank(loginUserVo.getUsername())||StringUtils.isBlank(loginUserVo.getPassword())){
            response.setResultCodeAndMessage("1001", "参数不能为空");
            return response;
        }

        if(loginUserVo.getPassword().length()!=32){
            response.setResultCodeAndMessage("1001", "请检查密码是否加密成md5后，再传入！");
            return response;
        }

        HospitalUser wheres=new HospitalUser();
        wheres.setUserName(loginUserVo.getUsername());
        wheres.setAvailable(1);
        wheres.setDelStatus(0);
        List<HospitalUser>  hospitalUsers=hospitalUserDao.select(wheres);
        if(CollectionUtils.isEmpty(hospitalUsers)){
            response.setResultCodeAndMessage("1002", "不存在用户"+loginUserVo.getUsername()+"的数据！");
            return response;
        }

        HospitalUser hospitalUser=hospitalUsers.get(0);
        String checkPassword=MD5Util.string2MD5(loginUserVo.getPassword()+hospitalUser.getSalt());
        if(!checkPassword.equals(hospitalUser.getPassword())){
            response.setResultCodeAndMessage("1002", "密码有误！");
            return response;
        }

        String sessionid=PKGenerator.generateId();
        sessionid=sessionid+"_"+loginUserVo.getDeviceType();
        SessionInfo sessionInfo=new SessionInfo();
        sessionInfo.setUserId(hospitalUser.getId());
        sessionInfo.setDeviceType(loginUserVo.getDeviceType());
        sessionInfo.setNickName(hospitalUser.getFullName());
        sessionInfo.setSignKey(PKGenerator.generateId().substring(8,24));
        sessionInfo.setSessionid(sessionid);
        sessionInfo.setSourceIp("");
        sessionInfo.setUserName(hospitalUser.getUserName());
        CacheService.setSessionInfo(sessionid, sessionInfo);
        response.setResultCodeAndMessageAndResult("0", "登录成功！",sessionInfo);

        return response;
    }



    /**
     * 系统用户登录
     * @param data
     * @interfaceName: yyt.base.user.sys.login
     * @return
     */
    public ResponseObject loginUserSys(String data) {
        logger.info("系统用户登录 json -->" + JsonUtils.toJsonString(data));
        ResponseObject response = new ResponseObject();
        LoginUserVoRequest loginUserVo=JsonUtils.parseObject(data,LoginUserVoRequest.class);

        if(StringUtils.isBlank(loginUserVo.getUsername())||StringUtils.isBlank(loginUserVo.getPassword())){
            response.setResultCodeAndMessage("1001", "参数不能为空");
            return response;
        }

        if(loginUserVo.getPassword().length()!=32){
            response.setResultCodeAndMessage("1001", "请检查密码是否加密成md5后，再传入！");
            return response;
        }

        OrgUser orgUser = new OrgUser();

        //如果渠道标志不为空，则增加渠道标注作为查询条件
        if(loginUserVo.getChannelType() != null){
            orgUser.setChannelType(loginUserVo.getChannelType());
        }

        orgUser.setLoginName(loginUserVo.getUsername());
        orgUser.setEnableFlag((short) 1);

        List<OrgUser> orgUsers = orgUserDao.select(orgUser);

        if(CollectionUtils.isEmpty(orgUsers)){
            response.setResultCodeAndMessage("1002", "不存在用户"+loginUserVo.getUsername()+"的数据！");
            return response;
        }

        OrgUser user = orgUsers.get(0);
        String checkPassword=MD5Util.string2MD5(loginUserVo.getPassword()+user.getSalt());
        if(!checkPassword.equals(user.getPassword())){
            response.setResultCodeAndMessage("1002", "密码有误！");
            return response;
        }

        //检查是否需要录入openId
        checkOrgUserInputOpenId(loginUserVo.getOpenId() , loginUserVo.getAppId() , user.getId(),loginUserVo.getAppCode());

        //查询user下orgId
        DeptUserRelation deptUserRelation = new DeptUserRelation();
        deptUserRelation.setUserId(user.getId());
        List<DeptUserRelation> deptUsers = deptUserRelationDao.select(deptUserRelation);
        if(deptUsers.size() > 0){

            List<SysUserOrg> sysUserOrgs = new ArrayList<SysUserOrg>();

            for (DeptUserRelation deptUser : deptUsers) {
                deptUser.setLastLoginTime(DateUtils.dateToString(new Date()));
                deptUserRelationDao.update(deptUser);

                SysUserOrg sysUserOrg = new SysUserOrg();
                sysUserOrg.setOrgId(deptUser.getOrgId());
                Org org = orgDao.selectById(deptUser.getOrgId());//增加查询orgCode
                sysUserOrg.setOrgCode(org.getOrgCode());
                sysUserOrg.setOrgName(deptUser.getOrgName());
                sysUserOrg.setOrgType(org.getOrgType());
                sysUserOrg.setSupDeliveryMethod(org.getSupDeliveryMethod());
                //增加上级机构的返回
                if(StringUtils.isNotBlank(org.getParentId())){
                    SysUserOrg sysUserOrgParent = new SysUserOrg();
                    Org orgParent = orgDao.selectById(org.getParentId());
                    if(orgParent != null){
                        sysUserOrgParent.setOrgCode(orgParent.getOrgCode());
                        sysUserOrgParent.setOrgName(orgParent.getOrgName());
                        sysUserOrgParent.setOrgType(orgParent.getOrgType());
                        sysUserOrgParent.setSupDeliveryMethod(orgParent.getSupDeliveryMethod());
                        sysUserOrg.setOrgParent(sysUserOrgParent);
                    }
                }
                sysUserOrgs.add(sysUserOrg);
            }

            String sessionid=PKGenerator.generateId();
            sessionid=sessionid+"_"+loginUserVo.getDeviceType();
            SessionInfo sessionInfo=new SessionInfo();
            sessionInfo.setUserId(user.getId());
            sessionInfo.setDeviceType(loginUserVo.getDeviceType());
            sessionInfo.setUserName(user.getUserName());
            sessionInfo.setNickName(user.getNickName());
            sessionInfo.setLoginName(user.getLoginName());
            sessionInfo.setSysUserOrgs(sysUserOrgs);
            sessionInfo.setSignKey(PKGenerator.generateId().substring(8,24));
            sessionInfo.setSessionid(sessionid);
            sessionInfo.setSourceIp("");
            sessionInfo.setUserName(user.getUserName());
            CacheService.setSessionInfo(sessionid,loginUserVo.getDeviceType(), sessionInfo);
            response.setResultCodeAndMessageAndResult("0", "登录成功！",sessionInfo);
        }else{
            response.setResultCodeAndMessageAndResult("50002", "登录失败！请检查deptUserRelation配置",null);
        }

        return response;
    }

    /**
     * 系统用户密码修改
     * @param data
     * @interfaceName: yyt.base.user.sys.password.update
     * @return
     */
    public ResponseObject updateUserSysPassword(String data) {
        logger.info("[UserServiceImpl.updateUserSysPassword] 入参：" + JsonUtils.toJsonString(data));
        ResponseObject response = new ResponseObject();
        LoginUserVoRequest loginUserVo=JsonUtils.parseObject(data,LoginUserVoRequest.class);

        if(StringUtils.isBlank(loginUserVo.getVerificationCode())||StringUtils.isBlank(loginUserVo.getPassword())){
            response.setResultCodeAndMessage("1001", "参数不能为空");
            return response;
        }

        if(loginUserVo.getPassword().length()!=32){
            response.setResultCodeAndMessage("1001", "请检查密码是否加密成md5后，再传入！");
            return response;
        }

        //验证码验证
        String verificationCode = CacheService.getGlobalKey("base", "verification_code", loginUserVo.getUsername());
        logger.info("系统用户密码修改, 缓存中获取验证码为：" + verificationCode);

        if (StringUtils.isNotBlank(verificationCode) && verificationCode.trim().equalsIgnoreCase(loginUserVo.getVerificationCode().trim())) {
            OrgUser orgUser = new OrgUser();
            orgUser.setLoginName(loginUserVo.getUsername());
            List<OrgUser> users = orgUserDao.select(orgUser);
            logger.info("系统用户密码修改接口, 根据username查询OrgUser结果为:" + JsonUtils.toJsonString(users));

            if(!CollectionUtils.isEmpty(users)) {
                orgUser = users.get(0);
                String newPasswrod = MD5Util.string2MD5(loginUserVo.getPassword() + orgUser.getSalt());
                orgUser.setPassword(newPasswrod);
                orgUserDao.update(orgUser);
                response.setResultCodeAndMessage(Response.SUCCESS_CODE, Response.SUCCESS_MESSAGE);
            }else{
                response.setResultCodeAndMessage("1002", "用户不存在，请先注册！");
                return response;
            }

        }else{
            response.setResultCodeAndMessage("1002", "验证码有误！");
            return response;
        }

        return response;
    }




    /**
     * 个人用户注册
     * @param data
     * @interfaceName: yyt.base.user.personal.register
     * @return
     */
    public ResponseObject registerUserPersonal(String data) {

        logger.info("个人用户注册接口, 入参data=" + data);
        ResponseObject response = new ResponseObject();
        String verificationCode=null;

        LoginUserVoRequest loginUserVo = JsonUtils.parseObject(data, LoginUserVoRequest.class);

        if(loginUserVo.getPassword().length()!=32){
            response.setResultCodeAndMessage("1001", "请检查密码是否加密成md5后，再传入！");
            return response;
        }

        if (StringUtils.isBlank(loginUserVo.getUsername()) || StringUtils.isBlank(loginUserVo.getPassword())
                ||loginUserVo.getChannelType()==Short.valueOf("1")?
                false:(StringUtils.isBlank(loginUserVo.getVerificationCode())
                ||!(loginUserVo.getChannelType()==Short.valueOf("2")))) {
            logger.info("个人用户注册接口, 入参username或verificationCode或password为空或channelType不正确");
            response.setResultCodeAndMessage("1001", "参数不能为空");
            return response;
        }
        if(loginUserVo.getChannelType()==Short.valueOf("2")){
            verificationCode = CacheService.getGlobalKey("base", "verification_code", loginUserVo.getUsername());
            logger.info("个人用户注册接口, 缓存中获取验证码为：" + verificationCode);
        }else {
            logger.info("个人用户注册接口, 无需从缓存中获取验证码");
        }
        if (loginUserVo.getChannelType()==Short.valueOf("1")?true:StringUtils.isNotBlank(verificationCode) && verificationCode.trim().
                equalsIgnoreCase(loginUserVo.getVerificationCode().trim())) {
            PersonalUser wheres = new PersonalUser();
            wheres.setLoginName(loginUserVo.getUsername());
            List<PersonalUser> personalUsers = personalUserDao.select(wheres);
            logger.info("个人用户注册接口, 根据username查询PersonalUser结果为:" + JsonUtils.toJsonString(personalUsers));

            PersonalUser pu = null;
            if (CollectionUtils.isEmpty(personalUsers)) {
                logger.info("个人用户注册接口, 不存在用户" + loginUserVo.getUsername() + "的数据");
                pu = new PersonalUser();
                pu.setId(IDUtils.getUUID32());
                pu.setLoginName(loginUserVo.getUsername());
                pu.setSalt("123456");
                pu.setPassword(MD5Util.string2MD5(loginUserVo.getPassword() + pu.getSalt()));
                pu.setUserName(loginUserVo.getUsername());
                pu.setNickName(loginUserVo.getUsername());
                pu.setMobile(loginUserVo.getUsername());
                pu.setOpenId(pu.getId());
                /** 默认启用 是否启用 0-禁用 1-启用', */
                pu.setEnableFlag(new Short("1"));
                pu.setRegisterTime(DateUtils.dateToString(new Date()));
                pu.setLastLoginTime(DateUtils.dateToString(new Date()));
                personalUserDao.insert(pu);
                response.setResultCodeAndMessageAndResult(Response.SUCCESS_CODE, "个人用户注册成功！",pu);
            } else {
                pu = personalUsers.get(0);
                response.setResultCodeAndMessageAndResult(Response.FAILURE_CODE, "该用户已存在！", pu);
                return response;
            }

            //检查个人用户是否需要录入openId
            checkPerUserInputOpenId(loginUserVo.getOpenId() , loginUserVo.getAppId() , pu.getId(),loginUserVo.getAppCode());
            //绑定患者与医生关系
            perUserBoneExtension(loginUserVo.getOpenId(),loginUserVo.getAppCode(),pu.getId(),loginUserVo.getUsername(),"1");

        }else{
            response.setResultCodeAndMessage("1002", "验证码有误！");
            return response;
        }

        return response;
    }

    /**
     * 系统用户注册
     * @param data
     * @interfaceName: yyt.base.user.sys.register
     * channelType 渠道类型: 0-骨科平台   1-骨科推广端   61-病案复印管理后台
     * @return
     */
    public ResponseObject registerUserSys(String data, String sessionId) {
        logger.info("系统用户注册接口, 入参data=" + data + ",sessionId=" + sessionId);

        ResponseObject response = new ResponseObject();

        if(StringUtils.isBlank(sessionId)){
            response.setResultCodeAndMessage("1001", "sessionId不能为空");
            logger.info("系统用户注册失败：sessionId不能为空");
            return response;
        }else{
            SessionInfo sessionInfo = CacheService.getSessionInfo(sessionId);

            logger.info("sessionInfo = " + JsonUtils.toJsonString(sessionInfo));

            if(sessionInfo == null){
                response.setResultCodeAndMessage("1001", "sessionId无效");
                logger.info("系统用户注册失败：sessionId无效");
                return response;
            }else if(!"admin61".equals(sessionInfo.getUserName())){
                response.setResultCodeAndMessage("1001", "当前用户无此操作权限");
                logger.info("系统用户注册失败：当前用户无此操作权限");
                return response;
            }
        }

        Map<String,String> vo = JsonUtils.parseObject(data,Map.class);

        String username = vo.get("username");
        String password = vo.get("password");
        String orgCode = vo.get("org_code");
        Short channelType = Short.parseShort(vo.get("channel_type"));

        if (StringUtils.isBlank(username) || StringUtils.isBlank(password) || StringUtils.isBlank(orgCode) || channelType == null) {
            logger.info("系统用户注册失败：入参username或password或org_code为空或channel_type为空");
            response.setResultCodeAndMessage("1001", "参数不能为空");
            return response;
        }

        if(password.length()!=32){
            response.setResultCodeAndMessage("1001", "请检查密码是否加密成md5后，再传入！");
            logger.info("系统用户注册失败：密码格式错误");
            return response;
        }

        //校验完参数合法性后，开始检查是否已存在该系统用户信息
        OrgUser orgUserWheres = new OrgUser();
        orgUserWheres.setLoginName(username);
        List<OrgUser> orgUsersFind = orgUserDao.select(orgUserWheres);
        logger.info("系统用户注册接口, 根据username查询OrgUser结果为:" + JsonUtils.toJsonString(orgUsersFind));

        OrgUser orgUser = null;
        if (CollectionUtils.isEmpty(orgUsersFind)) {
            logger.info("系统用户注册接口, 不存在用户" + username + "的数据,可以保存该新建用户");
            orgUser = new OrgUser();
            orgUser.setId(IDUtils.getUUID32());
            orgUser.setLoginName(username);
            orgUser.setSalt("123456");
            orgUser.setPassword(MD5Util.string2MD5(password + orgUser.getSalt()));
            orgUser.setUserName(username);
            orgUser.setNickName(username);
            /** 默认启用 是否启用 0-禁用 1-启用', */
            orgUser.setEnableFlag(new Short("1"));
            orgUser.setCreatedTime(DateUtils.dateToString(new Date()));
            orgUser.setUpdateTime(DateUtils.dateToString(new Date()));
            orgUser.setChannelType(channelType);

            Org orgWheres = new Org();
            orgWheres.setOrgCode(orgCode);
            List<Org> orgsFind = orgDao.select(orgWheres);
            if(orgsFind == null || orgsFind.size() == 0){
                response.setResultCodeAndMessage(Response.FAILURE_CODE, "找不到该org_code对应的机构");
                return response;
            }
            DeptUserRelation deptUserRelation = new DeptUserRelation();
            deptUserRelation.setId(IDUtils.getUUID32());
            deptUserRelation.setUserId(orgUser.getId());
            deptUserRelation.setLoginName(orgUser.getLoginName());
            deptUserRelation.setUserStatus(orgUser.getEnableFlag());
            deptUserRelation.setLastLoginTime(DateUtils.dateToString(new Date()));

            Org org = orgsFind.get(0);
            deptUserRelation.setOrgId(org.getId());
            deptUserRelation.setOrgName(org.getOrgName());

            orgUserDao.insert(orgUser);
            deptUserRelationDao.insert(deptUserRelation);
            response.setResultCodeAndMessage(Response.SUCCESS_CODE, "系统用户注册成功");
            return response;
        } else {
            orgUser = orgUsersFind.get(0);
            response.setResultCodeAndMessageAndResult(Response.FAILURE_CODE, "该用户已存在", orgUser);
            return response;
        }
    }

    /**
     * 系统用户查询
     * @param data
     * @interfaceName: yyt.base.user.sys.list
     * @return
     */
    public ResponseObject listUserSys(String data, String sessionId) {
        logger.info("系统用户查询, 入参data=" + data + ",sessionId=" + sessionId);
        ResponseObject response = new ResponseObject();
        try {
            Map<String,Object> resultMap = new HashMap<String,Object>();
            ListOrgUserRequestVo request = JsonUtils.parseObject(data,ListOrgUserRequestVo.class);
            Map<String, Object> params = new HashMap<String ,Object>();
            if (request.getUserType() !=null){
                params.put("userType",request.getUserType());
            }
            if (request.getDoctorName() !=null){
                params.put("userName",request.getDoctorName());
            }
            if (request.getOrgId() !=null){
                params.put("orgId",request.getOrgId());
            }
            if (request.getDeptId() !=null){
                params.put("deptId",request.getDeptId());
            }
            if (request.getMobile() !=null){
                params.put("mobile",request.getMobile());
            }
            if (com.alibaba.dubbo.common.utils.StringUtils.isNotEmpty(request.getUserIds())){
                String[] userIds = request.getUserIds().split(",");
                params.put("userIds",userIds);
            }
            if (request.getPageNum() !=null){
                params.put("pageNum",request.getPageNum());
            }
            if (request.getPageSize() !=null){
                params.put("pageSize",request.getPageSize());
            }
            if (request.getEnableFlag() !=null){
                params.put("enableFlag",request.getEnableFlag());
            }
            if (request.getChannelType() !=null){
                params.put("channelType",request.getChannelType());
            }

            List<OrgUserVo>datas = orgUserDao.getOrgUserList(params);
            resultMap.put("datas",datas);
            long datasCount = orgUserDao.getOrgUserListCount(params);
            resultMap.put("datasCount", String.valueOf(datasCount));
            response.setResultCodeAndMessageAndResult("0","成功",resultMap);
        }catch (Exception e){
            logger.error("查询系统用户信息失败",e);
            response.setResultCodeAndMessage(Response.FAILURE_CODE,e.getMessage());
        }
        return response;
    }

    /**
     * 个人用户无限制通用登录
     * @param data
     * @interfaceName: yyt.base.user.personal.general.login
     * @return
     */
    public ResponseObject loginUserPersonalGeneral(String data) {

        logger.info("个人用户无限制通用登录, 入参data=" + data);
        ResponseObject response = new ResponseObject();
        LoginPersonalRequest loginUserVo = JsonUtils.parseObject(data, LoginPersonalRequest.class);

        if (StringUtils.isBlank(loginUserVo.getName()) || StringUtils.isBlank(loginUserVo.getMobileNo())) {
            logger.info("个人用户无限制通用登录, 入参name或mobileNo为空");
            response.setResultCodeAndMessage("1001", "name或mobileNo参数不能为空");
            return response;
        }

        if(!IdCardUtils.validateCard(loginUserVo.getIdCardNo())){
            logger.info("个人用户无限制通用登录, 身份证验证不合法");
            response.setResultCodeAndMessage("1001", "身份证验证不合法");
        }

        if(!MobileUtil.isPhoneNum(loginUserVo.getMobileNo())){
            logger.info("个人用户无限制通用登录, 手机号验证不合法");
            response.setResultCodeAndMessage("1001", "手机号验证不合法");
        }

        PersonalUser wheres = new PersonalUser();
        wheres.setLoginName(loginUserVo.getMobileNo());
        wheres.setEnableFlag((short)1);
        List<PersonalUser> personalUsers = personalUserDao.select(wheres);
        logger.info("个人用户无限制通用登录, 根据username查询PersonalUser结果为:" + JsonUtils.toJsonString(personalUsers));
        PersonalUser pu = null;
        if(!CollectionUtils.isEmpty(personalUsers)){
            pu = personalUsers.get(0);
        }else{
            logger.info("个人用户无限制通用登录, 不存在用户" + loginUserVo.getMobileNo() + "的数据");
            pu = new PersonalUser();
            pu.setId(IDUtils.getUUID32());
            pu.setLoginName(loginUserVo.getMobileNo());
            pu.setSalt("123456");
            pu.setPassword(MD5Util.string2MD5(MD5Util.string2MD5("123456")+pu.getSalt()));
            pu.setUserName(loginUserVo.getName());
            pu.setNickName(loginUserVo.getName());
            pu.setMobile(loginUserVo.getMobileNo());
            pu.setIdCardNo(loginUserVo.getIdCardNo());
            pu.setAppId(loginUserVo.getAppId());
            pu.setOpenId(pu.getId());
            pu.setIdCardType(Short.valueOf("1"));
            pu.setIdCardNo(loginUserVo.getIdCardNo());
            pu.setUserType(Short.valueOf("1"));
            pu.setSex(IdCardUtils.getSexFlagByIdCard(loginUserVo.getIdCardNo()));
            pu.setBirth(IdCardUtils.getBirthByIdCard(loginUserVo.getIdCardNo()));
            /** 默认启用 是否启用 0-禁用 1-启用', */
            pu.setEnableFlag(new Short("1"));
            pu.setRegisterTime(DateUtils.dateToString(new Date()));
            pu.setLastLoginTime(DateUtils.dateToString(new Date()));
            personalUserDao.insert(pu);
        }

        //检查openId
        checkPerUserInputOpenId(loginUserVo.getOpenId() , loginUserVo.getAppId() , pu.getId(),loginUserVo.getAppCode());

        String sessionid = PKGenerator.generateId();
        sessionid=sessionid+"_"+loginUserVo.getDeviceType();
        SessionInfo sessionInfo = new SessionInfo();
        sessionInfo.setUserId(pu.getId());
        sessionInfo.setUserName(pu.getUserName());
        sessionInfo.setLoginName(pu.getLoginName());
        sessionInfo.setDeviceType(loginUserVo.getDeviceType());
        sessionInfo.setNickName(pu.getNickName());
        sessionInfo.setSignKey(PKGenerator.generateId().substring(8, 24));
        sessionInfo.setSessionid(sessionid);
        sessionInfo.setSourceIp("");
        CacheService.setSessionInfo(sessionid, sessionInfo);
        response.setResultCodeAndMessageAndResult("0", "登录成功！", sessionInfo);
        return response;
    }



    /**
     * 个人用户登录
     * @param data
     * @interfaceName: yyt.base.user.personal.login
     * @return
     */
    public ResponseObject loginUserPersonal(String data) {

        logger.info("个人用户登录接口, 入参data=" + data);
        ResponseObject response = new ResponseObject();
        LoginUserVoRequest loginUserVo = JsonUtils.parseObject(data, LoginUserVoRequest.class);

        if (StringUtils.isBlank(loginUserVo.getUsername()) || StringUtils.isBlank(loginUserVo.getPassword())) {
            logger.info("个人用户登录接口, 入参username或password为空");
            response.setResultCodeAndMessage("1001", "参数不能为空");
            return response;
        }

        if(loginUserVo.getPassword().length()!=32){
            response.setResultCodeAndMessage("1001", "请检查密码是否加密成md5后，再传入！");
            return response;
        }

        PersonalUser wheres = new PersonalUser();
        wheres.setLoginName(loginUserVo.getUsername());
        wheres.setEnableFlag((short)1);
        List<PersonalUser> personalUsers = personalUserDao.select(wheres);
        logger.info("个人用户登录接口, 根据username查询PersonalUser结果为:" + JsonUtils.toJsonString(personalUsers));
        if(CollectionUtils.isEmpty(personalUsers)){
            response.setResultCodeAndMessage("1002", "不存在用户"+loginUserVo.getUsername()+"的数据！请先注册");
            return response;
        }

        PersonalUser pu = personalUsers.get(0);
        String checkPassword=MD5Util.string2MD5(loginUserVo.getPassword()+pu.getSalt());
        if(!checkPassword.equals(pu.getPassword())){
            response.setResultCodeAndMessage("1002", "密码有误！");
            return response;
        }

        //检查openId
        checkPerUserInputOpenId(loginUserVo.getOpenId() , loginUserVo.getAppId() , pu.getId(),loginUserVo.getAppCode());
        //绑定患者与医生关系
        perUserBoneExtension(loginUserVo.getOpenId(),loginUserVo.getAppCode(),pu.getId(),loginUserVo.getUsername(),"1");

        String sessionid = PKGenerator.generateId();
        sessionid=sessionid+"_"+loginUserVo.getDeviceType();
        SessionInfo sessionInfo = new SessionInfo();
        sessionInfo.setUserId(pu.getId());
        sessionInfo.setUserName(pu.getUserName());
        sessionInfo.setLoginName(pu.getLoginName());
        sessionInfo.setDeviceType(loginUserVo.getDeviceType());
        sessionInfo.setNickName(pu.getNickName());
        sessionInfo.setSignKey(PKGenerator.generateId().substring(8, 24));
        sessionInfo.setSessionid(sessionid);
        sessionInfo.setSourceIp("");
        sessionInfo.setHeadImg(pu.getHeadImg());
        CacheService.setSessionInfo(sessionid, sessionInfo);
        response.setResultCodeAndMessageAndResult("0", "登录成功！", sessionInfo);
        return response;
    }




    /**
     * 个人用户密码修改
     * @param data
     * @interfaceName: yyt.base.user.personal.password.update
     * @return
     */
    public ResponseObject updateUserPersonalPassword(String data) {
        logger.info("[UserServiceImpl.updateUserPersonalPassword] 入参：" + JsonUtils.toJsonString(data));
        ResponseObject response = new ResponseObject();
        LoginUserVoRequest loginUserVo=JsonUtils.parseObject(data,LoginUserVoRequest.class);

        if(StringUtils.isBlank(loginUserVo.getVerificationCode())||StringUtils.isBlank(loginUserVo.getPassword())){
            response.setResultCodeAndMessage("1001", "参数不能为空");
            return response;
        }

        if(loginUserVo.getPassword().length()!=32){
            response.setResultCodeAndMessage("1001", "请检查密码是否加密成md5后，再传入！");
            return response;
        }

        //验证码验证
        String verificationCode = CacheService.getGlobalKey("base", "verification_code", loginUserVo.getUsername());
        logger.info("个人用户密码修改接口, 缓存中获取验证码为：" + verificationCode);

        if (StringUtils.isNotBlank(verificationCode) && verificationCode.trim().equalsIgnoreCase(loginUserVo.getVerificationCode().trim())) {
            PersonalUser personalUser = new PersonalUser();
            personalUser.setLoginName(loginUserVo.getUsername());
            List<PersonalUser> users = personalUserDao.select(personalUser);
            logger.info("个人用户密码修改接口, 根据username查询OrgUser结果为:" + JsonUtils.toJsonString(users));

            if(!CollectionUtils.isEmpty(users)) {
                personalUser = users.get(0);
                String newPasswrod = MD5Util.string2MD5(loginUserVo.getPassword() + personalUser.getSalt());
                personalUser.setPassword(newPasswrod);
                personalUserDao.update(personalUser);
                response.setResultCodeAndMessage(Response.SUCCESS_CODE, "密码修改成功！");
            }else{
                response.setResultCodeAndMessage("1002", "用户不存在，请先注册！");
                return response;
            }

        }else{
            response.setResultCodeAndMessage("1002", "验证码有误！");
            return response;
        }

        return response;
    }




    /**
     * 授权用户登录
     * @param data
     * @return
     */
    public ResponseObject loginUserAuth(String data) {
        String prefixStr = "个人授权登录登录接口, 入参data->" + data + "||";
        ResponseObject response = new ResponseObject();
        LoginAuthUserRequest loginUserVo = JsonUtils.parseObject(data, LoginAuthUserRequest.class);

        if (StringUtils.isBlank(loginUserVo.getOpenId())||loginUserVo.getDataSourceFlag()==null) {
            logger.info(prefixStr + "入参openid或dataSourceFlag不能为空");
            response.setResultCodeAndMessage("1001", "入参openid或dataSourceFlag不能为空");
            return response;
        }

        //检查下缓存上是否已经有，有的话，无须再重复查询数据库
        String cacheSessionId=CacheService.getCacheClient().getLoginAuthSessionIdCache(loginUserVo.getOpenId());
        if(!StringUtils.isBlank(cacheSessionId)){
            logger.info(prefixStr + "命中缓存第一层级OpenId:"+loginUserVo.getOpenId()+",CacheSessionId:"+cacheSessionId);
            SessionInfo sessionInfo=CacheService.getSessionInfo(cacheSessionId);
            if(sessionInfo!=null){
                logger.info(prefixStr + "命中缓存第二层级CacheSessionId:"+cacheSessionId+",sessionInfo:"+JSON.toJSONString(sessionInfo));
                response.setResultCodeAndMessageAndResult("0", "登录成功！", sessionInfo);
                return response;
            }else{
                logger.info(prefixStr + "无法命中缓存第二层级CacheSessionId:"+cacheSessionId+"删除该键值");
                CacheService.getCacheClient().deleteLoginAuthSessionIdCache(loginUserVo.getOpenId());
            }
        }else{
            logger.info(prefixStr + "无法命中缓存第一层级OpenId:"+loginUserVo.getOpenId());
        }

        PersonalUser pu = null;
        PersonalUserFamily family=null;

        //判断是否是自己系统的登录用户
        if ((loginUserVo.getOpenId().length() == 32 || MobileUtil.checkSimplePhone(loginUserVo.getOpenId())) && loginUserVo.getDataSourceFlag() == 3) {
            PersonalUser userWheres = new PersonalUser();
            if(MobileUtil.checkSimplePhone(loginUserVo.getOpenId())){
                userWheres.setLoginName(loginUserVo.getOpenId());
            }else{
                userWheres.setId(loginUserVo.getOpenId());
            }
            List<PersonalUser> personalUsers = personalUserDao.select(userWheres);
            if (CollectionUtils.isEmpty(personalUsers)) {
                logger.info(prefixStr + "系统用户并不存在");
                response.setResultCodeAndMessage("1001", "系统用户并不存在");
                return response;
            }
            pu = personalUsers.get(0);
        } else {
            PersonalUser userWheres = new PersonalUser();
            userWheres.setLoginName(loginUserVo.getOpenId());
            List<PersonalUser> personalUsers = personalUserDao.select(userWheres);
            if (CollectionUtils.isEmpty(personalUsers)) {//新增
                try {
                    logger.info(prefixStr + "开始新增个人数据");
                    pu = new PersonalUser();
                    pu.setId(IDUtils.getUUID32());
                    pu.setLoginName(loginUserVo.getOpenId());
                    pu.setSalt("123456");
                    pu.setPassword(MD5Util.string2MD5(MD5Util.string2MD5("123456") + pu.getSalt()));
                    pu.setUserName(loginUserVo.getUsername());
                    pu.setNickName(loginUserVo.getUsername());
                    pu.setMobile(loginUserVo.getMobile());
                    pu.setSex(loginUserVo.getSex());
                    pu.setUserType((short) 1);
                    pu.setBirth(IdCardUtils.getBirthByIdCard(loginUserVo.getIdCardNo()));
                    /** 默认启用 是否启用 0-禁用 1-启用', */
                    pu.setEnableFlag(new Short("1"));
                    pu.setIdCardType((short) loginUserVo.getIdCardType());
                    pu.setIdCardNo(loginUserVo.getIdCardNo());
                    pu.setRegisterTime(DateUtils.dateToString(new Date()));
                    pu.setLastLoginTime(DateUtils.dateToString(new Date()));
                    pu.setRealNameFlag(loginUserVo.getRealNameFlag());
                    pu.setOpenId(loginUserVo.getOpenId());
                    pu.setAppId(loginUserVo.getAuthAppId());
                    pu.setDataSourceFlag(loginUserVo.getDataSourceFlag());
                    pu.setAppCode(loginUserVo.getAppCode());
                    personalUserDao.insert(pu);
                    logger.info(prefixStr + "新增个人的数据成功:" + JSON.toJSONString(pu));
                } catch (Exception ex) {
                    logger.error(prefixStr + "个人授权登录登录接口插入个人的数据失败:" + ex.getMessage() + "," + data, ex);
                    response.setResultCodeAndMessage("1001", "新增用户异常:" + ex.getMessage());
                    return response;
                }

                //新增家人
                if (!StringUtils.isBlank(loginUserVo.getIdCardNo())) {
                    try{
                        family=new PersonalUserFamily();
                        family.setId(IDUtils.getUUID32());
                        family.setUserId(pu.getId());
                        family.setAddress(pu.getAddress());
                        family.setAppCode(loginUserVo.getAppCode());
                        family.setAppId(loginUserVo.getAuthAppId());
                        family.setBirth(pu.getBirth());
                        family.setCreatedTime(DateUtils.dateToString(new Date()));
                        family.setDataSourceFlag(loginUserVo.getDataSourceFlag());
                        family.setEnableFlag((short)1);
                        family.setIdCardNo(loginUserVo.getIdCardNo());
                        family.setIdCardType((short)loginUserVo.getIdCardType());
                        family.setMobile(loginUserVo.getMobile());
                        family.setNickName(loginUserVo.getUsername());
                        family.setUserName(loginUserVo.getUsername());
                        family.setUserType((short)1);
                        family.setOpenId(loginUserVo.getOpenId());
                        family.setRelationType((short)6);
                        family.setSex(loginUserVo.getSex());
                        family.setAge(IdCardUtils.getAgeByIdCard(loginUserVo.getIdCardNo()));
                        family.setBindInsuranceCardFlag(loginUserVo.getBindInsuranceCardFlag());
                        family.setInsuranceLoginName(loginUserVo.getInsuranceLoginName());
                        personalUserFamilyDao.insert(family);
                    }catch (RuntimeException rex){
                        logger.error(prefixStr + "个人授权登录登录接口插入本人的就诊数据失败:" + rex.getMessage() , rex);
                    }
                }

            } else {
                pu = personalUsers.get(0);
            }
        }

        //更新用户信息
        try {
            PersonalUser updatePersonalUser = new PersonalUser();
            updatePersonalUser.setId(pu.getId());
            updatePersonalUser.setLastLoginTime(DateUtils.dateToString(new Date()));

            //如果当前传入的用户姓名不为空，数据库存储的为空，则更新数据库的字段
            if (StringUtils.isBlank(pu.getUserName()) && StringUtils.isNotBlank(loginUserVo.getUsername())) {
                updatePersonalUser.setUserName(loginUserVo.getUsername());
                pu.setUserName(loginUserVo.getUsername());
            }

            //如果当前传入的用户手机号不为空，数据库存储的为空，则更新数据库的字段
            if (StringUtils.isBlank(pu.getMobile()) && StringUtils.isNotBlank(loginUserVo.getMobile())) {
                updatePersonalUser.setMobile(loginUserVo.getMobile());
            }

            //如果当前传入的用户性别不为空，数据库存储的为空，则更新数据库的字段
            if ((pu.getSex() == null || pu.getSex() == 3) && loginUserVo.getSex() != null && loginUserVo.getSex() != 3) {
                updatePersonalUser.setSex(loginUserVo.getSex());
                pu.setSex(loginUserVo.getSex());
            }

            //如果当前传入的身份证号不为空，数据库存储的为空，则更新数据库的字段
            if (StringUtils.isBlank(pu.getIdCardNo()) && StringUtils.isNotBlank(loginUserVo.getIdCardNo())) {
                updatePersonalUser.setIdCardType((short) loginUserVo.getIdCardType());
                updatePersonalUser.setIdCardNo(loginUserVo.getIdCardNo());
                updatePersonalUser.setRealNameFlag(loginUserVo.getRealNameFlag());
                updatePersonalUser.setBirth(IdCardUtils.getBirthByIdCard(loginUserVo.getIdCardNo()));
            }

            personalUserDao.update(updatePersonalUser);
        } catch (RuntimeException ex) {
            logger.error(prefixStr+"个人授权登录登录接口, 更新用户:" + JSON.toJSONString(pu) + "最后登录时间失败", ex);
        }

        //获取家人本人信息
        if(family==null){
            family=new PersonalUserFamily();
            try{
                PersonalUserFamily wheres=new PersonalUserFamily();
                wheres.setUserId(pu.getId());
                wheres.setRelationType((short)6);
                wheres.setEnableFlag((short)1);
                List<PersonalUserFamily> personalUserFamilys =  personalUserFamilyDao.select(wheres);
                if(!CollectionUtils.isEmpty(personalUserFamilys)){
                    family=personalUserFamilys.get(0);
                }
            }catch (RuntimeException rex){
                logger.error(prefixStr+"个人授权登录登录接口, 获取家人本人信息的时候，发生异常", rex);
            }
        }

        String sessionid = PKGenerator.generateId();
        sessionid = sessionid + "_" + loginUserVo.getDeviceType();
        SessionInfo sessionInfo = new SessionInfo();
        sessionInfo.setUserId(pu.getId());
        sessionInfo.setOpenId(pu.getOpenId());
        sessionInfo.setLoginName(pu.getLoginName());
        sessionInfo.setDeviceType(loginUserVo.getDeviceType());
        sessionInfo.setSignKey(PKGenerator.generateId().substring(8, 24));
        sessionInfo.setSessionid(sessionid);
        sessionInfo.setUserName(family.getUserName());
        sessionInfo.setNickName(family.getUserName());
        sessionInfo.setSex(family.getSex());
        sessionInfo.setUserType(family.getUserType());
        sessionInfo.setSourceIp("");
        sessionInfo.setAuthAppId(loginUserVo.getAuthAppId());
        sessionInfo.setBindInsuranceCardFlag(loginUserVo.getBindInsuranceCardFlag());
        sessionInfo.setInsuranceLoginName(loginUserVo.getInsuranceLoginName());
        CacheService.setSessionInfo(sessionid, sessionInfo);
        //缓存sessionid
        CacheService.getCacheClient().setLoginAuthSessionIdCache(loginUserVo.getOpenId(),sessionid);
        response.setResultCodeAndMessageAndResult("0", "登录成功！", sessionInfo);
        return response;
    }

    public ResponseObject convertUserPatcard(String data) {
        ResponseObject response = new ResponseObject();
        ConvertUserPatcardVoRequest cupRequest=JsonUtils.parseObject(data,ConvertUserPatcardVoRequest.class);
        try {
            Validator.getInstance().validate(cupRequest);
        } catch (ValidateException ex) {
            logger.info(" 数据校验失败:" + ex.getMessage() + "|入参:" + data + "！");
            logger.error("error", ex);
            response.setResultCodeAndMessage("1001", "数据校验失败:" + ex.getMessage() + "！");
            return response;
        }
        //如果是卡类型是身份证那么姓名不能为空
        if(cupRequest.getPatCardType() == 5){
            if(StringUtils.isBlank(cupRequest.getPatName())){
                response.setResultCodeAndMessage("1001", "数据校验失败:姓名不能为空");
                return response;
            }
        }

        PatientVo patientVo = new PatientVo();
        patientVo.setHospitalCode(cupRequest.getHospitalCode());
        patientVo.setPatName(cupRequest.getPatName());
        patientVo.setPatCardType(Short.toString(cupRequest.getPatCardType()));
        patientVo.setPatCardNo(cupRequest.getPatCardNo());
        ResCommon<PatientVoResponse> resCommon =  HisifaceService.getHisifaceClient().getPatient(patientVo);

        if (!"0".equals(resCommon.getResultCode())) {
            response.setResultCodeAndMessage("1002", "查询患者信息失败:"+resCommon.getResultMessage());
            return response;
        }
        PatientVoResponse patientVoResponse = resCommon.getResult();
        if (StringUtils.isBlank(patientVoResponse.getPatCardNo())) {
            response.setResultCodeAndMessage("1006", "查询患者信息失败，无卡号返回！");
            return response;
        }

        ConvertUserPatcardVoResponse convertUserPatcardVoResponse = new ConvertUserPatcardVoResponse();
        convertUserPatcardVoResponse.setPatCardNo(patientVoResponse.getPatCardNo());
        convertUserPatcardVoResponse.setPatCardType(Short.parseShort("1"));

        if (StringUtils.isBlank(patientVoResponse.getPatName())){
            convertUserPatcardVoResponse.setPatName(cupRequest.getPatName());
        }
        convertUserPatcardVoResponse.setPatName(patientVoResponse.getPatName());

        convertUserPatcardVoResponse.setPatMobile(patientVoResponse.getPatMobile());
        convertUserPatcardVoResponse.setPatIdNo(patientVoResponse.getPatIdNo());
        convertUserPatcardVoResponse.setHospitalCode(patientVoResponse.getHospitalCode());

        response.setResultCodeAndMessage("0","成功");
        response.setResultObject(convertUserPatcardVoResponse);
        return response;
    }

    /**
     * 用户验证码登录 yyt.base.user.personal.by.verification.code.login
     * @param data
     * @return
     */
    public ResponseObject loginUserPersonalByVerificationCode(String data) {
        logger.info("用户端验证码登录接口, 入参data=" + data);
        ResponseObject response = new ResponseObject();
        LoginUserVoRequest loginUserVo = JsonUtils.parseObject(data, LoginUserVoRequest.class);

        if (StringUtils.isBlank(loginUserVo.getUsername()) || StringUtils.isBlank(loginUserVo.getVerificationCode())) {
            logger.info("用户端验证码登录接口, 入参username或verificationCode为空");
            response.setResultCodeAndMessage("1001", "参数不能为空");
            return response;
        }

        String verificationCode = CacheService.getGlobalKey("base", "verification_code", loginUserVo.getUsername());
        logger.info("用户端验证码登录接口, 缓存中获取验证码为：" + verificationCode);

        if (StringUtils.isNotBlank(verificationCode)
                && verificationCode.trim().equalsIgnoreCase(loginUserVo.getVerificationCode().trim())) {
            PersonalUser wheres = new PersonalUser();
            wheres.setLoginName(loginUserVo.getUsername());
            List<PersonalUser> personalUsers = personalUserDao.select(wheres);
            logger.info("用户端验证码登录接口, 根据username查询PersonalUser结果为:" + JsonUtils.toJsonString(personalUsers));

            PersonalUser pu = null;
            if (CollectionUtils.isEmpty(personalUsers)) {
                logger.info("用户端验证码登录接口, 不存在用户" + loginUserVo.getUsername() + "的数据");
                pu = new PersonalUser();
                pu.setId(IDUtils.getUUID32());
                pu.setLoginName(loginUserVo.getUsername());
                pu.setSalt("123456");
                pu.setPassword(MD5Util.string2MD5(MD5Util.string2MD5("123456")+pu.getSalt()));
                pu.setUserName(loginUserVo.getUsername());
                pu.setNickName(loginUserVo.getUsername());
                pu.setMobile(loginUserVo.getUsername());
                /** 默认启用 是否启用 0-禁用 1-启用', */
                pu.setEnableFlag(new Short("1"));
                pu.setRegisterTime(DateUtils.dateToString(new Date()));
                pu.setLastLoginTime(DateUtils.dateToString(new Date()));

                personalUserDao.insert(pu);
            } else {
                pu = personalUsers.get(0);
            }

            //检查openId
            checkPerUserInputOpenId(loginUserVo.getOpenId() , loginUserVo.getAppId() , pu.getId(),loginUserVo.getAppCode());

            //绑定患者与医生关系
            perUserBoneExtension(loginUserVo.getOpenId(),loginUserVo.getAppCode(),pu.getId(),loginUserVo.getUsername(),"1");

            String sessionid = PKGenerator.generateId();
            sessionid=sessionid+"_"+loginUserVo.getDeviceType();
            SessionInfo sessionInfo = new SessionInfo();
            sessionInfo.setUserId(pu.getId());
            sessionInfo.setDeviceType(loginUserVo.getDeviceType());
            sessionInfo.setNickName(pu.getNickName());
            sessionInfo.setSignKey(PKGenerator.generateId().substring(8, 24));
            sessionInfo.setSessionid(sessionid);
            sessionInfo.setSourceIp("");
            sessionInfo.setUserName(pu.getUserName());
            sessionInfo.setHeadImg(pu.getHeadImg());
            CacheService.setSessionInfo(sessionid, sessionInfo);
            response.setResultCodeAndMessageAndResult("0", "登录成功！", sessionInfo);
        } else {
            response.setResultCodeAndMessage("1002", "验证码有误！");
            return response;
        }

        return response;
    }

    /**
     * 企业用户验证码登录 yyt.base.user.org.by.verification.code.login
     * @param data
     * @return
     */
    public ResponseObject loginUserOrgByVerificationCode(String data) {
        logger.info("医生端验证码登录接口, 入参data=" + data);
        ResponseObject response = new ResponseObject();
        LoginUserVoRequest loginUserVo = JsonUtils.parseObject(data, LoginUserVoRequest.class);

        // 校验入参，username-手机号，verification_code-验证码
        if (StringUtils.isBlank(loginUserVo.getUsername()) || StringUtils.isBlank(loginUserVo.getVerificationCode())) {
            response.setResultCodeAndMessage("1001", "参数不能为空");
            return response;
        }

        // 从缓存中获取验证码
        String verificationCode = CacheService.getGlobalKey("base", "verification_code", loginUserVo.getUsername());
        logger.info("医生端验证码登录接口, 缓存中获取验证码为：" + verificationCode);

        if (StringUtils.isNotBlank(verificationCode)
                && verificationCode.trim().equalsIgnoreCase(loginUserVo.getVerificationCode().trim())) {
            OrgUser wheres = new OrgUser();
            wheres.setLoginName(loginUserVo.getUsername());
            List<OrgUser> orgUsers = orgUserDao.select(wheres);
            logger.info("医生端验证码登录接口, 根据username查询OrgUser结果为:" + JsonUtils.toJsonString(orgUsers));

            OrgUser ou = null;
            if (CollectionUtils.isEmpty(orgUsers)) {
                logger.info("医生端验证码登录接口, 不存在用户" + loginUserVo.getUsername() + "的数据");
                response.setResultCodeAndMessage("1003", "该用户不存在！");
                return response;
            } else {
                ou = orgUsers.get(0);
            }

            //检查openId
            checkOrgUserInputOpenId(loginUserVo.getOpenId() , loginUserVo.getAppId() , ou.getId(),loginUserVo.getAppCode());

            String sessionid = PKGenerator.generateId();
            sessionid=sessionid+"_"+loginUserVo.getDeviceType();
            SessionInfo sessionInfo = new SessionInfo();
            sessionInfo.setUserId(ou.getId());
            sessionInfo.setDeviceType(loginUserVo.getDeviceType());
            sessionInfo.setNickName(ou.getNickName());
            sessionInfo.setSignKey(PKGenerator.generateId().substring(8, 24));
            sessionInfo.setSessionid(sessionid);
            sessionInfo.setSourceIp("");
            sessionInfo.setUserName(ou.getUserName());
            CacheService.setSessionInfo(sessionid, sessionInfo);
            response.setResultCodeAndMessageAndResult("0", "登录成功！", sessionInfo);
        } else {
            response.setResultCodeAndMessage("1002", "验证码有误！");
            return response;
        }

        return response;
    }

    /**
     * 用户登出 yyt.base.user.logout
     * @param data
     * @return
     */
    public ResponseObject logoutUser(String data, String sessionId) {
        logger.info("登出接口, 入参data=" + data + ", sessionId=" + sessionId);
        ResponseObject response = new ResponseObject();
        CacheService.delSessionKey(sessionId, "sessioninfo");
        return response;
    }

    /**
     * 获取登录短信验证码 yyt.base.user.verification.code.get
     *
     * @param data
     * @return
     */
    public ResponseObject getUserVerificationCode(String data, String sessionId) {
        logger.info("获取登录验证码接口, 入参data=" + data + ", sessionId=" + sessionId);
        ResponseObject response = new ResponseObject();

        LoginUserVoRequest loginUserVo = JsonUtils.parseObject(data, LoginUserVoRequest.class);

        if (StringUtils.isBlank(loginUserVo.getUsername())) {
            response.setResultCodeAndMessage("1001", "参数不能为空");
            return response;
        }

        // 发送短信
        String code = String.valueOf(Math.abs(PKGenerator.generateId().hashCode()));
        int i = code.length();
        if (i < 6) {
            code += "000000";
        }
        code = code.substring(0, 6);
        String msgStr = "{\"user_type\":\"5\",\"to_user\":\"" + loginUserVo.getUsername()
                + "\",\"msg_type\":90,\"msg_content\":{\"code\":\"" + code + "\"}}";
        MessageService.callUnderlineFromInternal("", "yyt.message.msg.sms.send", msgStr);

        Response cacheResponse = CacheService.setGlobalKey("base", "verification_code", loginUserVo.getUsername(), code, 120);

        logger.info("获取登录验证码接口, 生成验证码为：" + code + " -- CacheResponse:" + cacheResponse.getResultCode() + "; " + cacheResponse.getResultMessage());

        return response;
    }


    //检查系统用户是否需要录入openId
    public void checkOrgUserInputOpenId(String openId , String appId ,String userId,String appCode){
        if(StringUtils.isNotBlank(openId)){
            OrgUserOpenid openUser = new OrgUserOpenid();
            openUser.setAppId(appId);
            openUser.setOrgUserId(userId);
            List<OrgUserOpenid> userOpenids = orgUserOpenidDao.select(openUser);
            if(CollectionUtils.isEmpty(userOpenids)){
                openUser.setId(PKGenerator.generateId());
                openUser.setOpenId(openId);
                openUser.setAppCode(appCode);
                openUser.setCreatedTime(simpleDateFormat.format(new Date()));
                openUser.setUpdateTime(simpleDateFormat.format(new Date()));
                orgUserOpenidDao.insert(openUser);
            }else{
                OrgUserOpenid orgUserOpenid=userOpenids.get(0);
                orgUserOpenid.setOrgUserId(userId);
                orgUserOpenid.setAppCode(appCode);
                orgUserOpenid.setAppId(appId);
                orgUserOpenid.setOpenId(openId);
                orgUserOpenid.setUpdateTime(simpleDateFormat.format(new Date()));
                orgUserOpenidDao.update(orgUserOpenid);
            }
        }
    }


    //检查个人用户是否需要录入openId
    public void checkPerUserInputOpenId(String openId , String appId ,String userId,String appCode){
        if(StringUtils.isNotBlank(openId)){
            PersonalUserOpenid openUser = new PersonalUserOpenid();
            openUser.setAppId(appId);
            openUser.setPerUserId(userId);
            List<PersonalUserOpenid> userOpenids = personalUserOpenidDao.select(openUser);
            if(CollectionUtils.isEmpty(userOpenids)){
                openUser.setId(PKGenerator.generateId());
                openUser.setOpenId(openId);
                openUser.setAppCode(appCode);
                openUser.setCreatedTime(simpleDateFormat.format(new Date()));
                openUser.setUpdateTime(simpleDateFormat.format(new Date()));
                personalUserOpenidDao.insert(openUser);
            }else{
                PersonalUserOpenid personalUserOpenid=userOpenids.get(0);
                personalUserOpenid.setPerUserId(userId);
                personalUserOpenid.setAppCode(appCode);
                personalUserOpenid.setAppId(appId);
                personalUserOpenid.setOpenId(openId);
                personalUserOpenid.setUpdateTime(simpleDateFormat.format(new Date()));
                personalUserOpenidDao.update(personalUserOpenid);
            }
        }
    }

    public void perUserBoneExtension(String openId,String appCode,String userId,String loginName,String payMode){
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("personal_open_id" , openId);
        param.put("org_app_code" , appCode);
        param.put("pay_mode" , payMode);
        param.put("personal_user_id" , userId);
        param.put("personal_user_name" , loginName);
        param.put("type","1");
        logger.info("医生与患者绑定入参data=" + JsonUtils.toJsonString(param));
        Response response = BoneService.callHumpFromInternal("yyt.bone.bone.extension.bind", JsonUtils.toJsonString(param));
        logger.info("医生与患者绑定出参response=" + JsonUtils.toJsonString(response));
    }

    /**
     * 注册云医通用户
     * 入参：{username：手机号,id:userid}
     * yyt.base.user.yyt.register
     * @param data
     * @return
     */
    public ResponseObject registerUserYyt(String data) {
        logger.info("注册云医通用户接口, 入参data=" + data);
        ResponseObject response = new ResponseObject();
        Map<String,String> loginUserVo = JsonUtils.parseObject(data, Map.class);
        String id = loginUserVo.get("id");
        String userName = loginUserVo.get("user_name");

        if (StringUtils.isBlank(userName) || StringUtils.isBlank(id)) {
            logger.info("注册云医通用户登录接口, 入参username或id为空");
            response.setResultCodeAndMessage("1001", "参数不能为空");
            return response;
        }

        PersonalUser wheres = new PersonalUser();
        wheres.setId(id);
        wheres.setLoginName(userName);
        List<PersonalUser> personalUsers = personalUserDao.select(wheres);
        logger.info("注册云医通用户接口, 根据username查询PersonalUser结果为:" + JsonUtils.toJsonString(personalUsers));

        PersonalUser pu = null;
        if (CollectionUtils.isEmpty(personalUsers)) {
            logger.info("注册云医通用户接口, 不存在用户" + userName+ "的数据");
            pu = new PersonalUser();
            pu.setId(id);
            pu.setLoginName(userName);
            pu.setSalt("123456");
            pu.setPassword("123456");
            pu.setUserName(userName);
            pu.setNickName(userName);
            pu.setMobile(userName);
            pu.setEnableFlag(new Short("1"));
            pu.setRegisterTime(DateUtils.dateToString(new Date()));
            pu.setLastLoginTime(DateUtils.dateToString(new Date()));
            pu.setOpenId(id);

            personalUserDao.insert(pu);
        } else {
            pu = personalUsers.get(0);
        }

        response.setResultCodeAndMessageAndResult("0", "注册成功！", pu);


        return response;
    }

    /**
     * 是否本人 yyt.base.user.compare
     * @param data
     * @return
     */
    public ResponseObject compareUser(String data) {
        logger.info("判断是否本人，入参data=" + data);
        ResponseObject response = new ResponseObject();
        Map<String,String> resMap=new HashMap<>();
        Map<String, String> requestVo = JsonUtils.parseObject(data, Map.class);

        String idCardNo=requestVo.get("id_card_no");
        String encryptIdCardNo=requestVo.get("encrypt_id_card_no");

        if(StringUtils.isBlank(idCardNo)||StringUtils.isBlank(encryptIdCardNo)){
            response.buildResultCodeAndMessage("1001","查询失败，传入参数不能为空");
            return response;
        }

        if(idCardNo.equals(encryptIdCardNo)){
            resMap.put("owner_flag","1");
        }else{
            resMap.put("owner_flag","2");
        }
        response.buildResultCodeAndMessageAndResult("0","查询成功",JSON.toJSONString(resMap));
        return response;
    }

    /**
     * 解密用户的信息 yyt.base.user.info.descrypt.get
     * @param data
     * @return
     */
    public ResponseObject getUserInfoDescrypt(String data) {
        logger.info("解密用户的信息，入参data=" + data);
        ResponseObject response = new ResponseObject();
        Map<String, String> resMap = new HashMap<>();
        Map<String, String> requestVo = JsonUtils.parseObject(data, Map.class);

        String encryptIdCardNo = requestVo.get("encrypt_id_card_no");
        if(StringUtils.isBlank(encryptIdCardNo)){
            response.buildResultCodeAndMessage("1001","查询失败，传入参数不能为空");
            return response;
        }
        resMap.put("pat_sex",String.valueOf(IdCardUtils.getSexFlagByIdCard(encryptIdCardNo)));
        resMap.put("pat_age",String.valueOf(IdCardUtils.getAgeByIdCard(encryptIdCardNo)));
        String patBirth=IdCardUtils.getBirthByIdCard(encryptIdCardNo);
        if(patBirth!=null&&patBirth.length()==8){
            resMap.put("pat_birth",patBirth.substring(0,4)+"-"+patBirth.substring(4,6)+"-"+patBirth.substring(6,8));
        }else{
            resMap.put("pat_birth",patBirth);
        }
        resMap.put("id_card_no",encryptIdCardNo.substring(0,1)+"****************"+encryptIdCardNo.substring(encryptIdCardNo.length()-1));

        response.buildResultCodeAndMessageAndResult("0","查询成功",JSON.toJSONString(resMap));
        return response;
    }




}
